<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2022/3/22
 * Time: 10:52
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\api\model;

use app\common\model\TimeModel;
use Htlove\Jwt;
use think\Exception;
use think\facade\Log;

class WeixinUser extends TimeModel
{
    public function getUserByOpenid(array $data = [])
    {
        //查询是否存在 存在则返回 不存在则插入
        try {
            $wechat = $this->getUserInfo($data['openid']);
        } catch (\Exception $e) {
            throw new Exception("查询失败");
        }
        if ($wechat) {
            $ret = $wechat->toArray();
            $token = $this->jwt_wechat($ret);
            $ret['token'] = $token;
            return $ret;
        } else {
            try {
                $res = $this->save($data);
            } catch (\Exception $e) {
                throw new Exception("新增失败");
            }
            if ($res) {
                $result = $this->getUserInfo($data['openid']);
                if ($result) {
                    $ret = $result->toArray();
                    $token = $this->jwt_wechat($ret);
                    $ret['token'] = $token;
                    return $ret;
                } else {
                    throw new Exception("用户不存在");
                }
            } else {
                throw new Exception("增加失败");
            }
        }
    }

    /**
     * @param array $wechat
     * @return mixed
     */
    protected function jwt_wechat(array $wechat = [])
    {
        $time = time();
        return Jwt::getInstance()->getToken([
            'iss' => $wechat['openid'], //该JWT的签发者
            'iat' => $time, //签发时间
            'exp' => $time + 7200, //过期时间
            'nbf' => $time, //该时间之前不接收处理该Token
            'sub' => $wechat, //数据
            'jti' => md5(uniqid('JWT') . time()) //该Token唯一标识
        ]);
    }

    /**
     * @param array $data
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function updateByUserInfo(array $data = [])
    {
        $data['update_time'] = time();
        try {
            $result = $this->where('openid', $data['openid'])->update($data);
        } catch (\Exception $e) {
            Log::error($e->getMessage() . " " . $e->getFile() . " " . $e->getCode());
            throw new Exception("内部错误");
        }
        if ($result) {
            $res = $this->getUserInfo($data['openid']);
            if ($res) {
                $wechat = $res->toArray();
                $token = $this->jwt_wechat($wechat);
                $wechat['token'] = $token;
                return $wechat;
            } else {
                throw new Exception("用户不存在");
            }
        } else {
            throw new Exception("用户信息不存在");
        }
    }

    /**
     * @param string $openid
     * @return WeixinUser|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function getUserInfo(string $openid = '')
    {
        return $this->where('openid', $openid)
            ->find();
    }

    /**
     * @param string $openid
     * @param string $field
     * @return WeixinUser|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserByList(string $openid = '',string $field='*'){
        return $this
            ->field($field)
            ->where('openid',$openid)
            ->find();
    }
}